package com.linxianqin.springbootVue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linxianqin.springbootVue.domain.dto.SysUserDTO;
import com.linxianqin.springbootVue.domain.entity.SysUserRole;
import com.linxianqin.springbootVue.mapper.SysUserRoleMapper;
import com.linxianqin.springbootVue.service.SysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author lxq
 * @since 2020-12-13
 */
@Slf4j
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    /**
     * 删除用户与角色关联
     * @param userIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserRoleByUserIds(List<Long> userIds) {
        baseMapper.deleteUserRoleByUserIds(userIds);
    }
    /**
     * 新增用户角色信息
     *
     * @param userDTO 用户对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserRole(SysUserDTO userDTO) {
        Long[] roles = userDTO.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userDTO.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
//                log.info("保存的角色信息：{}",list);
                saveBatch(list,list.size());
            }
        }
    }
    /**
     * 删除用户与角色关联
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserRoleByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>().lambda();
        queryWrapper.eq(SysUserRole::getUserId,userId);
        baseMapper.delete(queryWrapper);
    }
}
